<template>
  <view class="product-detail-page">
    <u-navbar placeholder
              leftIcon="arrow-left"
              :title="$t('pages_product_detail_detail_msg_b4f5dba9')"
              @leftClick="goBack" />

    <!-- 加载状态 -->
    <u-loading-page :loading="loading" loading-text="加载中..."/>

    <scroll-view v-if="!loading && (productDetail.id || productDetail.outProductId)" 
                 scroll-y 
                 class="detail-content"
                 :style="{ height: scrollHeight + 'px' }">
      
      <!-- 商品图片轮播 -->
      <view class="product-image-section">
        <swiper v-if="imageList.length > 0" 
                class="image-swiper" 
                indicator-dots 
                autoplay 
                circular>
          <swiper-item v-for="(image, index) in imageList" :key="index">
            <image :src="image" 
                   class="product-main-image" 
                   mode="aspectFill" />
          </swiper-item>
        </swiper>
        <image v-else
               :src="productDetail.pic || '/static/images/default-product.png'" 
               class="product-main-image" 
               mode="aspectFill" />
      </view>

      <!-- 商品基本信息 -->
      <view class="product-info-section">
        <view class="product-price-box">
          <text class="current-price">¥{{ productDetail.price || '0.00' }}</text>
        </view>
        
        <view class="product-title">
          {{ productDetail.name || '商品名称' }}
        </view>
        
        <view class="product-meta">
          <view class="meta-item">
            <text class="product-id">商品编号: {{ productDetail.outProductId || productDetail.id }}</text>
          </view>
          <view class="meta-item" v-if="productDetail.unit">
            <text class="product-unit">单位: {{ productDetail.unit }}</text>
          </view>
          <view class="meta-item" v-if="productDetail.weight">
            <text class="product-weight">重量: {{ productDetail.weight }}kg</text>
          </view>
          <view class="meta-item" v-if="productDetail.productCategoryName">
            <text class="product-category">分类: {{ productDetail.productCategoryName }}</text>
          </view>
          <view class="meta-item" v-if="productDetail.brand && productDetail.brand.name">
            <text class="product-brand">品牌: {{ productDetail.brand.name }}</text>
          </view>
          <view class="meta-item">
            <text :class="['product-status', productDetail.publishStatus == 1 ? 'status-on' : 'status-off']">
              {{ productDetail.publishStatus == 1 ? '在售' : '下架' }}
            </text>
          </view>
        </view>
      </view>

      <!-- 商品属性 -->
      <!-- <view class="product-attrs-section" v-if="productAttrs.length > 0">
        <view class="section-title">商品属性</view>
        <view class="attrs-list">
          <view v-for="attr in productAttrs" :key="attr.name" class="attr-group">
            <text class="attr-name">{{ attr.name }}:</text>
            <view class="attr-options">
              <text v-for="option in attr.options" 
                    :key="option.name" 
                    class="attr-option"
                    v-if="option.name">
                {{ option.name }}
              </text>
            </view>
          </view>
        </view>
      </view> -->

      <!-- SKU列表 -->
      <!-- <view class="product-skus-section" v-if="productDetail.skus && productDetail.skus.length > 0">
        <view class="section-title">规格选择</view>
        <view class="skus-list">
          <view v-for="sku in productDetail.skus" :key="sku.outSkuId" class="sku-item">
            <image :src="sku.pic || productDetail.pic || '/static/images/default-product.png'" class="sku-image" mode="aspectFill" />
            <view class="sku-info">
              <view class="sku-specs">
                <text v-for="(value, key) in parseSkuSpData(sku.spData)" :key="key" class="spec-tag">
                  {{ key }}: {{ value }}
                </text>
              </view>
              <view class="sku-meta">
                <view class="sku-price">¥{{ sku.price }}</view>
                <view class="sku-stock">库存: {{ sku.stock || 0 }}</view>
              </view>
            </view>
          </view>
        </view>
      </view> -->

      <!-- 商品详情HTML -->
      <view class="product-detail-section" v-if="productDetail.detailMobileHtml || productDetail.detailHtml">
        <view class="section-title">商品详情</view>
        <rich-text :nodes="productDetail.detailMobileHtml || productDetail.detailHtml" class="detail-html"/>
      </view>

      <!-- 底部占位，避免被固定按钮遮挡 -->
      <view class="bottom-placeholder"/>
    </scroll-view>

    <!-- 空状态 -->
    <u-empty v-if="!loading && !productDetail.id && !productDetail.outProductId" 
             :text="$t('pages_product_detail_detail_desc_e629e007')"
             class="empty-state" />

    <!-- 底部操作栏 -->
    <view class="bottom-actions" v-if="!loading && (productDetail.id || productDetail.outProductId)">
      <view class="action-buttons">
        <!-- <view class="contact-button" @click="onContact">
          <u-icon name="phone" size="20" color="#666" />
          <text>联系客服</text>
        </view> -->
        <view class="buy-button" @click="onBuyNow">
          立即购买
        </view>
      </view>
    </view>

    <!-- 规格选择弹窗 -->
    <view v-if="showSpecModal" class="spec-modal-overlay" @click="closeSpecModal">
      <view class="spec-modal" @click.stop="">
        <!-- 商品信息 -->
        <view class="spec-product-info">
          <image :src="productDetail.pic || '/static/images/default-product.png'" 
                 class="spec-product-image" 
                 mode="aspectFill" />
          <view class="spec-product-details">
            <view class="spec-product-name">{{ productDetail.name }}</view>
            <view class="spec-product-price">¥{{ currentPrice }}</view>
            <view class="spec-product-stock">库存：{{ currentStock }} 件</view>
          </view>
          <view class="spec-close-btn" @click="closeSpecModal">×</view>
        </view>

        <!-- 规格选择 -->
        <view class="spec-attrs" v-if="productAttrs.length > 0">
          <view v-for="(attr, index) in productAttrs" :key="index" class="spec-attr-group">
            <view class="spec-attr-name">{{ attr.name }}</view>
            <view class="spec-attr-options">
              <view 
                v-for="(option, optionIndex) in attr.options" 
                :key="optionIndex"
                v-if="option.name"
                class="spec-attr-option"
                :class="{ active: selectedSpecs[attr.name] === option.name }"
                @click="selectSpec(attr.name, option.name)"
              >
                {{ option.name }}
              </view>
            </view>
          </view>
        </view>

        <!-- 数量选择 -->
        <view class="spec-quantity">
          <view class="spec-quantity-label">数量</view>
          <view class="spec-quantity-control">
            <view class="quantity-btn" 
                  :class="{ disabled: quantity <= 1 }" 
                  @click="decreaseQuantity">-</view>
            <view class="quantity-input">{{ quantity }}</view>
            <view class="quantity-btn" 
                  :class="{ disabled: quantity >= currentStock }" 
                  @click="increaseQuantity">+</view>
          </view>
        </view>

        <!-- 确认按钮 -->
        <view class="spec-confirm">
          <button class="spec-confirm-btn" 
                  :class="{ disabled: !matchedSku }" 
                  @click="confirmSpecSelection">
            立即购买
          </button>
        </view>
      </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import productApi from '@/api/modules/product'

export default {
  name: 'Product-Detail',
  computed: {
    ...mapState({
      systemInfo: (state) => state.app.systemInfo,
    }),
    scrollHeight() {
      // 计算滚动区域高度：屏幕高度 - 状态栏 - 导航栏 - 底部操作栏
      return this.systemInfo.windowHeight - this.systemInfo.statusBarHeight - 44 - 100
    }
  },
  data() {
    return {
      productId: null,
      productDetail: {},
      loading: false,
      showSpecModal: false, // 显示规格选择弹窗
      selectedSpecs: {}, // 选中的规格
      quantity: 1, // 选择数量
    }
  },
  computed: {
    // 处理图片列表
    imageList() {
      const images = []
      if (this.productDetail.pic) {
        images.push(this.productDetail.pic)
      }
      if (this.productDetail.albumPics) {
        const albumImages = this.productDetail.albumPics.split(',').filter(img => img && img.trim())
        images.push(...albumImages)
      }
      return [...new Set(images)] // 去重
    },
    
    // 处理商品属性
    productAttrs() {
      if (!this.productDetail.productAttr) return []
      try {
        return JSON.parse(this.productDetail.productAttr) || []
      } catch (e) {
        console.error('解析productAttr失败:', e)
        return []
      }
    },
    
    // 根据选中规格找到对应的SKU
    matchedSku() {
      if (!this.productDetail.skus || this.productDetail.skus.length === 0) return null
      const selectedSpecsStr = JSON.stringify(this.selectedSpecs)
      return this.productDetail.skus.find(sku => sku.spData === selectedSpecsStr)
    },
    
    // 当前选择的价格
    currentPrice() {
      if (this.matchedSku) {
        return this.matchedSku.price
      }
      return this.productDetail.price || 0
    },
    
    // 当前库存
    currentStock() {
      if (this.matchedSku) {
        return this.matchedSku.stock || 0
      }
      return 999 // 默认库存
    }
  },
  onLoad(options) {
    this.productId = options.id
    if (this.productId) {
      this.getProductDetail()
    }
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },

    async getProductDetail() {
      if (!this.productId) return
      
      try {
        this.loading = true
        const res = await productApi.getDetail(this.productId)
        console.log('商品详情数据:', res)
        
        if (res && res.product) {
          // 处理嵌套的数据结构
          this.productDetail = {
            ...res.product,
            skus: res.skus || [],
            brand: res.brand
          }
          console.log('设置商品详情:', this.productDetail)
          // 动态设置页面标题
          if (res.product.name) {
            uni.setNavigationBarTitle({
              title: res.product.name.length > 10 ? res.product.name.substring(0, 10) + '...' : res.product.name
            })
          }
        } else {
          console.log('商品数据为空或格式错误:', res)
          this.$utils.toast(this.$t('pages_product_detail_detail_msg_997875d3'))
        }
      } catch (error) {
        console.error('获取商品详情失败:', error)
        this.$utils.toast(this.$t('pages_product_detail_detail_desc_7c6d7ac6'))
      } finally {
        this.loading = false
      }
    },

    onContact() {
      // 联系客服功能
      uni.showModal({
        title: this.$t('pages_product_detail_detail_msg_b6606015'),
        content: '是否拨打客服电话：400-123-4567？',
        success: (res) => {
          if (res.confirm) {
            uni.makePhoneCall({
              phoneNumber: '400-123-4567',
              fail: () => {
                this.$utils.toast(this.$t('pages_product_detail_detail_msg_8dfe7814'))
              }
            })
          }
        }
      })
    },

    parseSkuSpData(spDataStr) {
      if (!spDataStr) return {}
      try {
        return JSON.parse(spDataStr) || {}
      } catch (e) {
        console.error('解析SKU spData失败:', e)
        return {}
      }
    },

    onBuyNow() {
      // 检查商品状态
      if (this.productDetail.publishStatus !== 1) {
        this.$utils.toast(this.$t('pages_product_detail_detail_msg_1b81eea4'))
        return
      }
      
      if (!this.productDetail.id && !this.productDetail.outProductId) {
        this.$utils.toast(this.$t('pages_product_detail_detail_msg_a5005fc4'))
        return
      }
      
      // 如果有SKU，显示规格选择弹窗
      if (this.productDetail.skus && this.productDetail.skus.length > 0) {
        this.showSpecSelection()
      } else {
        // 没有SKU，直接创建订单
        this.createDirectOrder()
      }
    },

    // 显示规格选择弹窗
    showSpecSelection() {
      this.selectedSpecs = {}
      this.quantity = 1
      this.showSpecModal = true

      // 初始化规格选择（默认选择第一个有效选项）
      if (this.productAttrs.length > 0) {
        this.productAttrs.forEach(attr => {
          if (attr.options && attr.options.length > 0) {
            const validOption = attr.options.find(option => option.name)
            if (validOption) {
              this.$set(this.selectedSpecs, attr.name, validOption.name)
            }
          }
        })
      }
    },

    // 关闭规格选择弹窗
    closeSpecModal() {
      this.showSpecModal = false
      this.selectedSpecs = {}
      this.quantity = 1
    },

    // 选择规格
    selectSpec(attrName, optionName) {
      this.$set(this.selectedSpecs, attrName, optionName)
    },

    // 增加数量
    increaseQuantity() {
      if (this.quantity < this.currentStock) {
        this.quantity++
      }
    },

    // 减少数量
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--
      }
    },

    // 确认选择规格
    confirmSpecSelection() {
      if (!this.matchedSku) {
        uni.showToast({
          title: this.$t('pages_category_category_desc_7d66143e'),
          icon: 'none'
        })
        return
      }

      // 构造订单数据
      const orderData = {
        goodsList: [{
          id: this.productDetail.id,
          title: this.productDetail.name,
          image: this.productDetail.pic,
          price: this.currentPrice,
          number: this.quantity,
          specs: this.selectedSpecs,
          sku: this.matchedSku,
          outProductId: this.productDetail.outProductId,
          outSkuId: this.matchedSku.outSkuId
        }],
        totalQuantity: this.quantity,
        totalPrice: this.currentPrice * this.quantity,
        note: '',
        receiveInfo: null // 需要用户选择收货地址
      }

      console.log('创建订单数据:', orderData)
      
      this.closeSpecModal()
      
      // 跳转到订单创建页面
      const params = encodeURIComponent(JSON.stringify(orderData))
      this.$utils.router({
        url: `/pages/user/order/create?params=${params}`
      })
    },

    // 直接创建订单（无SKU规格的商品）
    createDirectOrder() {
      // 构造订单数据
      const orderData = {
        goodsList: [{
          id: this.productDetail.id,
          title: this.productDetail.name,
          image: this.productDetail.pic,
          price: this.productDetail.price,
          number: 1,
          specs: null,
          sku: null,
          outProductId: this.productDetail.outProductId,
          outSkuId: null
        }],
        totalQuantity: 1,
        totalPrice: this.productDetail.price,
        note: '',
        receiveInfo: null // 需要用户选择收货地址
      }

      console.log('创建直接订单数据:', orderData)
      
      // 跳转到订单创建页面
      const params = encodeURIComponent(JSON.stringify(orderData))
      this.$utils.router({
        url: `/pages/user/order/create?params=${params}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.product-detail-page {
  background: #f5f5f5;
  min-height: 100vh;
}

.detail-content {
  background: #f5f5f5;
}

.product-image-section {
  background: #fff;
  margin-bottom: 20rpx;
}

.image-swiper {
  height: 600rpx;
}

.product-main-image {
  width: 100%;
  height: 600rpx;
}

.product-info-section {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.product-price-box {
  margin-bottom: 20rpx;
}

.current-price {
  font-size: 36rpx;
  font-weight: bold;
  color: #007aff;
}

.product-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  line-height: 1.5;
  margin-bottom: 20rpx;
}

.product-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.meta-item {
  flex: 0 1 auto;
}

.product-id,
.product-unit,
.product-weight,
.product-category,
.product-brand {
  font-size: 24rpx;
  color: #999;
}

.product-status {
  font-size: 22rpx;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
}

.status-on {
  background: #e8f5e8;
  color: #52c41a;
}

.status-off {
  background: #fff2f0;
  color: #ff4757;
}

.product-detail-section,
.product-attrs-section,
.product-skus-section {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
  padding-bottom: 10rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.detail-content-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
  text-align: justify;
}

.params-list {
  .param-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
  }
  
  .param-label {
    font-size: 26rpx;
    color: #666;
    flex-shrink: 0;
  }
  
  .param-value {
    font-size: 26rpx;
    color: #333;
    text-align: right;
  }
}

.attrs-list {
  .attr-group {
    margin-bottom: 24rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .attr-name {
    font-size: 26rpx;
    color: #333;
    font-weight: 600;
    margin-bottom: 12rpx;
    display: block;
  }
  
  .attr-options {
    display: flex;
    flex-wrap: wrap;
    gap: 12rpx;
  }
  
  .attr-option {
    font-size: 24rpx;
    color: #666;
    background: #f5f5f5;
    padding: 8rpx 16rpx;
    border-radius: 20rpx;
  }
}

.skus-list {
  .sku-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
  }
  
  .sku-image {
    width: 80rpx;
    height: 80rpx;
    border-radius: 8rpx;
    margin-right: 20rpx;
    flex-shrink: 0;
  }
  
  .sku-info {
    flex: 1;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
  }
  
  .sku-specs {
    display: flex;
    flex-wrap: wrap;
    gap: 8rpx;
    flex: 1;
  }
  
  .spec-tag {
    font-size: 22rpx;
    color: #666;
    background: #f0f0f0;
    padding: 4rpx 8rpx;
    border-radius: 8rpx;
  }
  
  .sku-meta {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 8rpx;
  }
  
  .sku-price {
    font-size: 26rpx;
    font-weight: bold;
    color: #ff4d4f;
  }
  
  .sku-stock {
    font-size: 22rpx;
    color: #999;
  }
}

.detail-html {
  line-height: 1.6;
  font-size: 28rpx;
}

.bottom-placeholder {
  height: 120rpx;
}

.empty-state {
  padding-top: 200rpx;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  border-top: 1rpx solid #f0f0f0;
  z-index: 100;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.contact-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 12rpx;
  min-width: 120rpx;
  
  text {
    font-size: 22rpx;
    color: #666;
    margin-top: 8rpx;
  }
}

.buy-button {
  flex: 1;
  background: linear-gradient(135deg, #007aff, #005bb5);
  color: #fff;
  text-align: center;
  padding: 25rpx;
  border-radius: 50rpx;
  font-size: 30rpx;
  font-weight: 600;
  box-shadow: 0 8rpx 20rpx rgba(0, 122, 255, 0.3);
  
  &:active {
    transform: scale(0.98);
  }
}

// 规格选择弹窗
.spec-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  z-index: 1000;
}

.spec-modal {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  width: 100%;
  max-height: 80vh;
  overflow-y: auto;
  padding: 32rpx;
  position: relative;
}

.spec-product-info {
  display: flex;
  align-items: flex-start;
  margin-bottom: 32rpx;
  position: relative;

  .spec-product-image {
    width: 120rpx;
    height: 120rpx;
    border-radius: 8rpx;
    margin-right: 16rpx;
  }

  .spec-product-details {
    flex: 1;

    .spec-product-name {
      font-size: 32rpx;
      color: #333;
      font-weight: 500;
      margin-bottom: 8rpx;
      line-height: 1.4;
    }

    .spec-product-price {
      font-size: 36rpx;
      color: #007aff;
      font-weight: 600;
      margin-bottom: 8rpx;
    }

    .spec-product-stock {
      font-size: 26rpx;
      color: #666;
    }
  }

  .spec-close-btn {
    position: absolute;
    top: -8rpx;
    right: -8rpx;
    width: 48rpx;
    height: 48rpx;
    background: #f5f5f5;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    color: #666;
    font-weight: bold;
  }
}

.spec-attrs {
  margin-bottom: 32rpx;

  .spec-attr-group {
    margin-bottom: 24rpx;

    .spec-attr-name {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 16rpx;
      font-weight: 500;
    }

    .spec-attr-options {
      display: flex;
      flex-wrap: wrap;
      gap: 12rpx;
    }

    .spec-attr-option {
      padding: 16rpx 24rpx;
      border: 1px solid #ddd;
      border-radius: 8rpx;
      font-size: 26rpx;
      color: #333;
      background: #fff;
      min-width: 80rpx;
      text-align: center;
      transition: all 0.3s ease;

      &.active {
        border-color: #007aff;
        color: #007aff;
        background: rgba(0, 122, 255, 0.1);
      }

      &:active {
        transform: scale(0.95);
      }
    }
  }
}

.spec-quantity {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 32rpx;

  .spec-quantity-label {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
  }

  .spec-quantity-control {
    display: flex;
    align-items: center;
    border: 1px solid #ddd;
    border-radius: 8rpx;
    overflow: hidden;

    .quantity-btn {
      width: 64rpx;
      height: 64rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      color: #333;
      background: #f8f8f8;
      transition: all 0.3s ease;

      &.disabled {
        color: #ccc;
        background: #f5f5f5;
      }

      &:not(.disabled):active {
        background: #e0e0e0;
      }
    }

    .quantity-input {
      width: 80rpx;
      height: 64rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      color: #333;
      border-left: 1px solid #ddd;
      border-right: 1px solid #ddd;
      background: #fff;
    }
  }
}

.spec-confirm {
  .spec-confirm-btn {
    width: 100%;
    height: 88rpx;
    background: #007aff;
    color: white;
    border: none;
    border-radius: 44rpx;
    font-size: 32rpx;
    font-weight: 500;
    transition: all 0.3s ease;

    &.disabled {
      background: #ccc;
      opacity: 0.6;
    }

    &:not(.disabled):active {
      transform: scale(0.98);
    }
  }
}
</style>